const app = getApp();
const templateArr = [""];
export const initPay = () => new Promise(resolve => {
  if (templateArr.length === 1) {
    initFn().then(res => {
      resolve(res);
    });
  }
});
export const initFn = () => new Promise(resolve => {
  getTemplateParams({
    type: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
  }).then(data => {
    if (data.errCode === "0") {
      templateArr.push(...data.data);
      resolve(data.list);
    } else {
      xhs.showToast({
        title: data.errInfo,
        icon: "none",
        mask: true
      });
    }
  });
});

/**
 * 获取指定template 不能在初始化中调用
 * @param types {Array<String|Number>}
 * @returns { Array }
 */
export const getTemplateAsync = types => types.reduce((prev, curr) => prev.concat(templateArr[curr] ? templateArr[curr] : []), []);

/**
 *
 * @param url {String}
 * @param params {Object}
 * @returns {Promise<unknown>}
 */
export const getOrderId = (url, params) => new Promise(resolve => {
  app.$getData(url, params).then(data => {
    if (data.errCode == 0) {
      let result = data.data;
      xhs.setStorageSync("orderId", {
        orderId: result.orderId,
        orderType: result.orderType
      });
      resolve(result);
    } else {
      xhs.showToast({
        icon: "none",
        title: data.errInfo
      });
    }
  });
});

/**
 *
 * @param {Object} data
 * @param {Number} payType 0 requestPayment  1 requestOrderPayment
 * @param {Object<Function>} callback
 * @returns {Promise<unknown>}
 */
export const pay = (data, callback, payType = 0) => new Promise((resolve, reject) => {
  let payTypeString = payType == 0 ? "requestPayment" : "requestOrderPayment";
  xhs[payTypeString](Object.assign(data, {
    success: ({
      errMsg
    }) => {
      if (errMsg == payTypeString + ":ok") {
        xhs.showModal({
          title: "提示",
          content: "支付成功",
          showCancel: false,
          success() {
            if (callback && typeof callback === "function") {
              callback();
            } else {
              resolve();
            }
          }
        });
      }
    },
    fail: ({
      errMsg
    }) => {
      reject();
      if (errMsg !== payTypeString + ":fail cancel") {
        errMsg = errMsg.replace(payTypeString + ":fail ", "");
        xhs.showModal({
          title: "提示",
          content: errMsg,
          showCancel: false
        });
      }
    }
  }));
});

/**
 *
 * @param types {Array<String|Number>}
 * @param params {Object}
 * @param url {String}
 * @param content { String }
 * @param returnCode { String }
 * @returns {Promise<unknown>}
 */
export const subscribeMessage = (types, params, url, content = "您没有开启订阅消息, 将无法收到服务消息, 点击确定继续支付", returnCode) => new Promise(resolve => {
  params.templateIds = [];
  const tmplIds = getTemplateAsync(types);
  if (tmplIds.length === 0 || app.globalData.sysinfo.environment && app.globalData.sysinfo.environment == "wxwork") {
    url ? resolve(getOrderId(url, params)) : resolve(params);
  } else {
    xhs.requestSubscribeMessage({
      tmplIds,
      success: res => {
        for (let i in tmplIds) {
          if (res[tmplIds[i]] === "accept") {
            params.templateIds.push(tmplIds[i]);
          }
        }
        if (url) {
          resolve(getOrderId(url, params));
          setTemplateParams({
            templateIds: params.templateIds
          });
        } else {
          if (returnCode) {
            //返回code
            setTemplateParams(params).then(res => {
              resolve(res);
            });
          } else {
            setTemplateParams(params);
            resolve(params);
          }
        }
      },
      fail() {
        xhs.showModal({
          title: "提示",
          content,
          success({
            confirm
          }) {
            if (confirm) {
              if (url) {
                resolve(getOrderId(url, params));
                setTemplateParams({
                  templateIds: params.templateIds
                });
              } else {
                if (returnCode) {
                  //返回code
                  setTemplateParams(params).then(res => {
                    resolve(res);
                  });
                } else {
                  setTemplateParams(params);
                  resolve(params);
                }
              }
            }
          }
        });
      }
    });
  }
});
export const setTemplateParams = res => new Promise(resolve => {
  app.$getData("/user/subscribe-message/set-user-subscribe-message", res).then(data => {
    resolve(data);
  });
});
export const getTemplateParams = data => new Promise(resolve => {
  // const TYPE_ORDER = '3071';//订单成功通知
  // const TYPE_AFTER_SALE = '2755';//售后处理通知
  // const TYPE_GROUP_RESULT = '2757';//拼团结果通知
  // const TYPE_LUCK_DRAW_RESULT = '1565';//中奖结果通知
  // const TYPE_EMPLOYEE_RESULT = '2648';//入驻申请结果通知
  // const TYPE_ACTIVITY_STARTS_RESULT = '3537';//活动开始通知
  // const TYPE_WISH_FULFIL_RESULT = '28943';//任务完成通知
  // const TYPE_CONSULTATION_REPLY = '3426';//咨询回复通知
  // const TYPE_NEW_CLIENT_ACCESS = '28843';//新客户访问提醒
  // const TYPE_RECOMMENDED_EARNINGS = '5244';//推荐领红包(下单成功后，给下单机构员工的备货通知)
  // const TYPE_QQLIVE_SUBSCRIPTION = '9350';//直播订阅消息
  // const TYPE_PRESELL_BALANCE_NOTICE = '9381';//预售尾款通知
  // const TYPE_ORDER_DELIVERY = '610'; //订单发货提醒
  // const TYPE_ORDER_REWARD = '20350'; //商品带货操作结果通知(下单成功后，带单用户，带单员工通知)
  // const TYPE_ORDER_REWARD = '3537'; //用户在报名时，需要授权一下订阅消息模板，当时间达到提醒时间时，推送消息给用户
  // const TYPE_AUDIT_RESULT = '27921'; //审核结果通知
  // const TYPE_CONFIRM_QUOTATION = '29332'; //报价单确认通知
  //   '5596' =>会员卡过期提醒
  // *  '16513' =>优惠券过期提醒
  //   '612' =>提现成功通知
  //   '1776' =>预约成功通知
  //   '38255' =>预约取消成功通知
  let arr = ["", 3071, 2755, 2757, 1565, 2648, 3537, 28943, 3426, 28843, 5244, 9350, 9381, 610, 20350, 3537, 27921, 29332, 5596, 16513, 612, 1776, 38255];
  let tids = [];
  data.type.forEach(type => {
    tids.push(arr[type]);
  });
  let tmData = xhs.getStorageSync("subscribeMessage");
  if (tmData) {
    resolve(tmData, arr);
  } else {
    app.$getData("/user/subscribe-message/get-subscribe-template-id", {
      tids
    }).then(data => {
      xhs.setStorageSync("subscribeMessage", data);
      resolve(data, arr);
    });
  }
});